import { useEffect, useState } from 'react';
import styles from './index.module.less';
import SearchForm from './components/serchForm';
import { Button, Form, Image, Modal, Table, message } from 'antd';
import { addUser, delUser, getUserList } from '../../services/museumUser';

const Index = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [codeVisable, setCodeVisable] = useState(false);
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  const [addLoading, setAddLoading] = useState(false);
  const [loading, setLoading] = useState(false);
    
  const columns = [
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
    },
    {
      title: '电话',
      dataIndex: 'phonenumber',
      key: 'phonenumber',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      render: (_t: any, user: any) => (<Button onClick={() => handlerDelUser(user.uuid)} type='link'>删除</Button>)
    },
  ];

  const handlerDelUser = (uuid: string) => {
    Modal.confirm({
      title: '删除用户',
      content: '是否删除该用户',
      okText: '删除',
      cancelText: '取消',
      onOk: async () => {
        try {
          await delUser({uuid});
        } catch (error: any) {
          message.warning(error.message);
        }
        handlerSearch();
      },
    });
  };

  const handlerAddUser = async ()  => {
    setAddLoading(true);
    try {
      const res = await addUser();
      if (res.data.code === 200) {
        setQrCodeUrl(`https://open.weixin.qq.com${res.data.data}`);
        setCodeVisable(true);
      }
    } catch (error) {
      console.log(error);
    }
    setAddLoading(false);
  };

  const queryList = async (page: number) => {
    setLoading(true);
    const data = form.getFieldsValue();
    try {
      const res = await getUserList({ ...data, page });
      if (res.data.code === 200) {
        setDataSource(res.data.data.rows);
        // setTotal(res.data.total);
      }
    } catch (error) {
      
    }
    setLoading(false);
  };

  const handlerSearch = () => {
    queryList(1);
  }

  useEffect(() => {
    queryList(1);
  }, []);

  return (
    <div className={styles.container}>
      <SearchForm form={form} onSearch={handlerSearch} />
      <Button loading={addLoading} onClick={handlerAddUser} type="primary">添加用户</Button>
      <div className={styles.table}>
        <Table
          dataSource={dataSource}
          columns={columns}
          loading={loading}
          rowKey="uuid"
        />
      </div>
      <Modal
        title="授权登录二维码"
        open={codeVisable}
        onCancel={() => setCodeVisable(false)}
        footer={null}
      >
        <Image preview={false} src={qrCodeUrl} />
      </Modal>
    </div>
  );
};

export default Index;
